package com.lqk.nio.groupchat;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;

public class GroupChatClientThread implements Runnable {
    private Selector selector;

    public GroupChatClientThread(Selector selector) {
        this.selector = selector;
    }

    @Override
    public void run() {
        try {
            for (;;){
                int readChannels = selector.select();
                if (readChannels==0){
                    continue;
                }
                if (readChannels>0){// 有可用通道，有事件发生的通道
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        if (key.isReadable()){
                            readMsg(key);
                        }
                        // 手动删除SelectionKey，避免重复操作
                        iterator.remove();
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    // 读取服务器端发送的消息
    public void readMsg(SelectionKey key) throws IOException {
        System.out.println("============");
        // 得到相关的通道
        SocketChannel channel =(SocketChannel) key.channel();
        // 得到Buffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        int readLength = channel.read(byteBuffer);
        String msg="";
        if (readLength>0){
            // 读写模式转换
            byteBuffer.flip();
            // 把读到的缓冲区的数据转成字符串
            msg += Charset.forName("UTF-8").decode(byteBuffer);
        }
        // 4 将channel再次注册到选择器上，监听可读状态
        channel.register(selector,SelectionKey.OP_READ);
        // 5 接收消息并打印
        if (msg.length()>0){
            System.out.println(msg);
        }
    }

}
